package net.cityside.summer.web.lang;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.context.Context;
import org.apache.velocity.tools.Scope;
import org.apache.velocity.tools.ToolboxFactory;
import org.apache.velocity.tools.config.XmlFactoryConfiguration;
import org.apache.velocity.tools.view.ViewToolContext;
import org.springframework.web.context.support.ServletContextResource;

public class VelocityToolsView extends
		org.springframework.web.servlet.view.velocity.VelocityToolboxView {

	@Override
	protected Context createVelocityContext(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// Create a ViewToolContext instance since ChainedContext is deprecated
		// in Velocity Tools 2.0.
		ViewToolContext velocityContext = new ViewToolContext(
				getVelocityEngine(), request, response, getServletContext());
		velocityContext.putAll(model);

		// TODO 每次都要读配置文件，构造工厂……
		if (getToolboxConfigLocation() != null) {
			XmlFactoryConfiguration cfg = new XmlFactoryConfiguration();
			// 因为这里需要getServletContext()，因此需要为每次请求构造一次？
			cfg.read(new ServletContextResource(getServletContext(),
					getToolboxConfigLocation()).getURL());
			ToolboxFactory toolboxFactory = cfg.createFactory();
			// 还要每次都创建Toolbox
			velocityContext.addToolbox(toolboxFactory
					.createToolbox(Scope.APPLICATION));
			velocityContext.addToolbox(toolboxFactory
					.createToolbox(Scope.REQUEST));
			velocityContext.addToolbox(toolboxFactory
					.createToolbox(Scope.SESSION));
		}

		return velocityContext;
	}

}